#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>

#include "psd_conn.h"
#include "psd_conn_null.h"

static int psd_conn_null_write(psdConn *sink, const void *buf, size_t len, int flags);
static int psd_conn_null_read(psdConn *src, void *buf, size_t len, int flags);
static int psd_conn_null_shutdown(psdConn *conn, uint8_t direction);
static int psd_conn_null_setbufsize(psdConn *conn, uint8_t direction, int size);
static int psd_conn_null_settimeout(psdConn *conn, uint8_t direction, int seconds);
static void psd_conn_null_free(psdConn *conn);

psdConn *psd_alloc_conn_null(int fd) {
	psdConn *new_conn;

	new_conn = psd_conn_alloc();
	if (!new_conn)
		goto error_exit;

	new_conn->stats_private = psd_conn_stats_alloc_def();
	if (!new_conn->stats_private)
		goto error_exit2;

	new_conn->conn_private = NULL;

	new_conn->protocol = "NULL";

	new_conn->read2 = psd_conn_null_read;
	new_conn->write2 = psd_conn_null_write;
	new_conn->shutdown2 = psd_conn_null_shutdown;
	new_conn->setbufsize2 = psd_conn_null_setbufsize;
	new_conn->settimeout2 = psd_conn_null_settimeout;
	new_conn->get_msg2 = psd_conn_default_get_msg;
	new_conn->send_msg2 = psd_conn_default_send_msg;
	new_conn->get_stat2 = psd_conn_default_get_stat;

	return new_conn;

error_exit2:
	free(new_conn);
error_exit:
	return NULL;
}

static int psd_conn_null_write(psdConn *sink, const void *buf, size_t len, int flags) {
	((psdConn_defStats *)sink->stats_private)->bytes_written += len;
	return len;
}

static int psd_conn_null_read(psdConn *src, void *buf, size_t len, int flags) {
	((psdConn_defStats *)src->stats_private)->bytes_read += len;
	bzero(buf, len);
	return len;
}

static int psd_conn_null_shutdown(psdConn *conn, uint8_t direction) {
	// psd_event_connection_end(conn);
	return 0;
}

static int psd_conn_null_setbufsize(psdConn *conn, uint8_t direction, int size) {
	return size;
}

static int psd_conn_null_settimeout(psdConn *conn, uint8_t direction, int seconds) {
	return seconds;
}

static void psd_conn_null_free(psdConn *conn) {
	free(conn->stats_private);
	psd_free_conn(conn);
}
